package lol.clann.minecraft.springboot.plugin.service;

import com.ruoshui.utils.json.JsonUtils;
import lol.clann.minecraft.springboot.api.service.FlagService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用来管理各种flag
 *
 * @author: zyp
 * @date: 2020/10/19 11:15 上午
 */
@Service
public class FlagServiceImpl implements FlagService {

    private Map<String, String> cache = new HashMap<>();

    @Override
    public synchronized void register(String key) {
        if (cache.containsKey(key)) {
            return;
        }
        cache.put(key, null);
    }

    @Override
    public synchronized String unregister(String key) {
        return cache.remove(key);
    }

    @Override
    public synchronized String set(String key, Object value) {
        if (!cache.containsKey(key)) {
            throw new IllegalStateException("请注册后再使用");
        }
        if (value == null || value instanceof String) {
            return cache.put(key, (String) value);
        }
        return cache.put(key, JsonUtils.writeValueAsString(value));
    }

    @Override
    public synchronized <T> T get(String key, Class<T> type) {
        if (!cache.containsKey(key)) {
            throw new IllegalStateException("请注册后再使用");
        }
        String v = get(key);
        if (v == null) {
            return null;
        }
        return JsonUtils.readValue(v, type);
    }

    @Override
    public synchronized <T> T get(String key, Class<T> type, T defaultValue) {
        if (!cache.containsKey(key)) {
            throw new IllegalStateException("请注册后再使用");
        }
        T v = get(key, type);
        if (v == null) {
            return defaultValue;
        }
        return v;
    }

    @Override
    public synchronized String get(String key) {
        if (!cache.containsKey(key)) {
            throw new IllegalStateException("请注册后再使用");
        }
        return cache.get(key);
    }

    @Override
    public synchronized List<String> getAllFlagKeys() {
        return new ArrayList<>(cache.keySet());
    }

    @Override
    public synchronized Map<String, String> getAllFlags() {
        return new HashMap<>(cache);
    }
}
